<?php

namespace app\api\controller;

use app\admin\model\Orders as OrdersModel;
use app\admin\service\PhoneService;
use app\common\controller\Api;
use app\model\User;
use app\admin\model\Orders;
use app\admin\model\Cloudphone;
use app\api\service\PayService;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function createOrder()
    {
        $userInfo = getJWT(getHeaderToken());
        if($userInfo['id'] == 0){
            //未登录 无法判断是否加入
            return dataReturn(-1,'请重新登录',[]);
        }
        $params = input();

        $phoneModel = new Cloudphone();
        $ordersModel = new Orders();
        //判断是否存在某个云手机是空闲的
        $phoneData = $phoneModel->where([
            'status'=>1,
            'is_delete'=>-1,
            'is_use_allday'=>-1,
        ])->select();
        if(empty($phoneData)){
            //查询最近的一次可预约时间
            $phoneData = $phoneModel->where([
                'status'=>1,
                'is_delete'=>-1,
            ])->select();
            if(empty($phoneData)){
                return dataReturn(-1,'平台暂无开放的云机',[]);
            }

            $end_time = date("Y-m-d H:i:s",time()+3600*24*365);
            foreach ($phoneData as $onePhone){
                $oneOrder = $ordersModel->where('phone_id',$onePhone['id'])->where('status','<=',$ordersModel::STATUS_HASPAY)->find();
                if($oneOrder && $oneOrder['end_time'] < $end_time){
                    $end_time = $oneOrder['end_time'];
                }
            }
            return dataReturn(-1,"目前云机已约满，请在{$end_time}来进行购买云机",[]);
        }else{
            //找出一个可用的云机
            $phone_id = 0;
            $instance_code = '';
            $end_time = date("Y-m-d H:i:s",time()+3600*24*365);
            foreach ($phoneData as $onePhone){
                $oneOrder = $ordersModel->where('phone_id',$onePhone['id'])->where('status','<=',$ordersModel::STATUS_HASPAY)->find();
                if(empty($oneOrder)){
                    $phone_id = $onePhone['id'];
                    $instance_code = $onePhone['instance_code'];
                    break;
                }
                if($oneOrder && $oneOrder['end_time'] < $end_time){
                    $end_time = $oneOrder['end_time'];
                }
            }

            if(empty($phone_id)){
                return dataReturn(-1,"目前云机已约满，请在{$end_time}来进行购买云机",[]);
            }
            $order_no = date("Ymdhis") . mt_rand(1000, 9999);
            $package_item_id = $params['item_id'];
            $item_data = db('package_item')->where('id',$package_item_id)->find();
            $buy_nums = $params['num'];
            $s_time = time();
            $start_time = date("Y-m-d H:i:s");
            if($item_data['type'] == 1){
                //小时
                $time_num = $item_data['num']*$buy_nums;
                $e_time = $s_time+3600*$time_num;
            }else{
                $time_num = $item_data['num']*$buy_nums;
                $e_time = $s_time+3600*24*$time_num;
            }
            $buy_type = 1;
            if($params['weixin_pay'] == 1){
                $buy_type = 1;
            }else if($params['qianbao_pay'] == 1){
                $buy_type = 2;
                $userData = db('user')->where('id',$userInfo['id'])->find();
                $total_hours = $userData['total_hours'];
                $buy_total_hours = $item_data['num']*$buy_nums;
                if($total_hours < $buy_total_hours){
                    return dataReturn(-1,"您钱包里面的小时数不足以抵扣",[]);
                }
            }


            $orderData = [
                'order_no'=>$order_no,
                'phone_id'=>$phone_id,
                'instance_code'=>$instance_code,
                'package_id'=>$item_data['package_id'],
                'package_item_id'=>$item_data['id'],
                'package_item_name'=>$item_data['name'],
                'type'=>$item_data['type'],
                'user_id'=>$userInfo['id'],
                'parent_id'=>$userInfo['parent_id'] ?? 0,
                'status'=>$ordersModel::STATUS_WAITPAY,
                "nums"=>$item_data['num'],
                "buy_nums"=>$buy_nums,
                "buy_type"=>$buy_type,
                "total_price"=>round($buy_nums*$item_data['money'],2),
                "start_time"=>$start_time,
                "end_time"=>date("Y-m-d H:i:s",$e_time),
                "create_time"=>$start_time,
            ];
            $order_id = $ordersModel->insertGetId($orderData);

            $pay_status = config('global.pay_status');
            $pay = new PayService($order_id,$userInfo['id'],$pay_status);

            if($pay_status == 0 || $buy_type == 2){
                //0元支付则是直接成功
                $data = $pay->afterOrder();
                if($buy_type == 2){
                    $buy_total_hours = $item_data['num']*$buy_nums;
                    $userData = db('user')->where('id',$userInfo['id'])->find();
                    db('user')->where('id',$userInfo['id'])->update(['total_hours'=>$userData['total_hours']-$buy_total_hours]);
                }
            }else{

                $data = $pay->pay();
            }

            return json($data);
        }

    }
    public function closeOrder(){
        $order_no = input('order_no','');
        if(empty($order_no)){
            return dataReturn(-1,'参数非法');
        }
        $userInfo = getJWT(getHeaderToken());
        if($userInfo['id'] == 0){
            //未登录 无法判断是否加入
            return dataReturn(-1,'请重新登录',[]);
        }
        $ordersModel = new Orders();
        $orderData = $ordersModel->where('user_id',$userInfo['id'])->where('order_no',$order_no)->find();
        if(empty($orderData)){
            return dataReturn(-1,'该订单不属于您的');
        }
        $ordersModel->where('id',$orderData['id'])->update(['status'=>$ordersModel::STATUS_HASCLOSE]);
        return dataReturn(0,'订单已取消',[]);
    }
    public function xufeiOrder()
    {
        $userInfo = getJWT(getHeaderToken());
        if($userInfo['id'] == 0){
            //未登录 无法判断是否加入
            return dataReturn(-1,'请重新登录',[]);
        }
        $params = input();

        $order_id = $params['order_id'];
        $package_item_id = $params['item_id'];
        $phoneModel = new Cloudphone();
        $ordersModel = new Orders();

        $orderData = $ordersModel->where('id',$order_id)->find();
        if($orderData['status'] != $ordersModel::STATUS_HASPAY){
            return dataReturn(-1,'订单状态已结束不可续费',[]);
        }

        $phone_id = $orderData['phone_id'];
        $instance_code = $orderData['instance_code'];
        $item_data = db('package_item')->where('id',$package_item_id)->find();
        $buy_nums = $params['num'];
        $s_time = time();
        $old_s_time = strtotime($orderData['end_time']);
        $start_time = date("Y-m-d H:i:s");
        if($item_data['type'] == 1){
            //小时
            $time_num = $item_data['num']*$buy_nums;
            $e_time = $old_s_time+3600*$time_num;
        }else{
            $time_num = $item_data['num']*$buy_nums;
            $e_time = $old_s_time+3600*24*$time_num;
        }
        $order_no = date("Ymdhis") . mt_rand(1000, 9999);
        $orderData = [
            'order_no'=>$order_no,
            'phone_id'=>$phone_id,
            'instance_code'=>$instance_code,
            'package_id'=>$item_data['package_id'],
            'package_item_id'=>$item_data['id'],
            'package_item_name'=>$item_data['name'],
            'type'=>$item_data['type'],
            'user_id'=>$userInfo['id'],
            'status'=>$ordersModel::STATUS_WAITPAY,
            "nums"=>$item_data['num'],
            "buy_nums"=>$buy_nums,
            "total_price"=>round($buy_nums*$item_data['money'],2),
            "start_time"=>$start_time,
            "end_time"=>date("Y-m-d H:i:s",$e_time),
            "create_time"=>$start_time,
            'remark'=>"续费<>{$order_id}"
        ];


        $new_order_id = $ordersModel->insertGetId($orderData);

        $pay_status = config('global.pay_status');
        $pay = new PayService($new_order_id,$userInfo['id'],$pay_status);
        if($pay_status == 0){
            //0元支付则是直接成功
            $data = $pay->afterOrder();
        }else{

            $data = $pay->pay();
        }

        return json($data);
    }

    public function getList(){
        $userInfo = getJWT(getHeaderToken());
        if($userInfo['id'] == 0){
            //未登录 无法判断是否加入
            return dataReturn(-555,'请重新登录',[]);
        }
        $orderModel = new Orders();
        $orderData = $orderModel->where('user_id',$userInfo['id'])->where('status','<',$orderModel::STATUS_HASCLOSE)->order("id desc")->limit(40)->select();
        return dataReturn(0,'ok',$orderData);
    }
    /**
     * 授权登录
     */
    public function authlogin(){
        $userInfo = getJWT(getHeaderToken());
        if($userInfo['id'] == 0){
            //未登录 无法判断是否加入
            return dataReturn(-555,'请重新登录',[]);
        }
        $order_id = input('order_id',0);

        $orderData = db('cloudphone_order')->where('id',$order_id)->find();
        $phoneData = db('cloudphone')->where('id',$orderData['phone_id'])->find();
        if(empty($orderData)){
            return dataReturn(-1,'查无订单');
        }
        if($orderData['status'] != OrdersModel::STATUS_HASPAY){
            return dataReturn(-1,'订单状态已结束');
        }
        if($orderData['user_id'] != $userInfo['id']){
            return dataReturn(-1,'订单非法查询');
        }
        if($phoneData['init_status'] == 2){
            return dataReturn(-1,'机器正在就绪中，稍等1分钟');
        }

        $uuid = $orderData['user_id'];
        if(!empty($orderData['server_token'])){
            $serverToken = $orderData['server_token'];
            $loginurl = request()->domain()."/index/phone/index?uuid={$uuid}&token={$serverToken}";
            return dataReturn(0,'ok',['phoneurl'=>$loginurl,'end_time'=>mb_substr($orderData['end_time'],5,11)]);
        }else{
            $phoneServiceHandle = new PhoneService();
            $onlineTime = strtotime($orderData['end_time']) - time();
            if($onlineTime < 0){
                return dataReturn(-1,'云机已到期了');
            }
            $serverToken = $phoneServiceHandle->serverToken($uuid,$orderData['instance_code'],$onlineTime);
            if($serverToken){
                $loginurl = request()->domain()."/index/phone/index?uuid={$uuid}&token={$serverToken}";
                db('cloudphone_order')->where('id',$order_id)->update(['server_token'=>$serverToken]);
                return dataReturn(0,'ok',['phoneurl'=>$loginurl,'end_time'=>mb_substr($orderData['end_time'],5,11)]);
            }else{
                return dataReturn(-1,$phoneServiceHandle->errorMsg);
            }
        }

    }
}
